import { SystemConfig } from "../serve/config"
import CryptoJS from 'crypto-js'

export const __VERSION__ = window['__VERSION__'] as string
export const __PUBLIC_PATH__ = window['__PUBLIC_PATH__'] as string
export const __LOGOUT__ = window['__LOGOUT__'] as string
export const __ADMIN__ = window['__ADMIN__'] as string
export const __ON_LINK__ = window['__ON_LINK__'] as (link: string, open: boolean, alert: {(msg: any): void}) => (e: MouseEvent) => void
export const __CONFIG__ = window['__CONFIG__'] as SystemConfig['client']

export const doEncode = (ctx: any) => {
    const { encrypt, encrypt_key } = __CONFIG__
    if (encrypt) {
        const key = CryptoJS.enc.Utf8.parse(encrypt_key)
        const iv = CryptoJS.enc.Utf8.parse('ABCDEF0123456789')
        const srcs = CryptoJS.enc.Utf8.parse(JSON.stringify(ctx));
        return {
            __content: CryptoJS.AES.encrypt(srcs, key, {
                iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7,
            }).ciphertext.toString().toUpperCase(),
        }
    }
    return ctx
}
export const doDecode = (body: ReturnType<typeof doEncode>) => {
    const { encrypt, encrypt_key } = __CONFIG__
    if (encrypt && body.__content) {
        const key = CryptoJS.enc.Utf8.parse(encrypt_key)
        const iv = CryptoJS.enc.Utf8.parse('ABCDEF0123456789')
        const encryptedHexStr = CryptoJS.enc.Hex.parse(body.__content);
        const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
        const jsonStr = CryptoJS.AES.decrypt(
            srcs, key, {
                iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7,
            }
        ).toString(CryptoJS.enc.Utf8)
        return JSON.parse(jsonStr)
    }
    return body
}
